﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Hangjing.Common;
using Newtonsoft.Json;
using System.Text;
using System.IO;
using Hangjing.Model;
using Hangjing.DBUtility;
using Hangjing.SQLServerDAL;
using System.Collections.Specialized;
using Hangjing.EleAPIV2;
using Hangjing.WebCommon;
using Hangjing.BaiduMapServerAPI;

/// <summary>
/// 百度外卖通知接口
/// </summary>
public partial class api_baidu_api : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();


        HJlog.toLog("\r\n百度外卖推送");


        System.IO.Stream stream = Request.InputStream;//这是你获得的流
        if (stream != null && stream.Length > 10)
        {

            string jsondata = "";
            using (StreamReader reader = new StreamReader(stream))
            {
                jsondata = reader.ReadToEnd(); ;
            }

            Hangjing.AppLog.AppLog.Info("推送数据stream.Length ：" + jsondata);
            
        }




        Response.Write("{\"message\": \"ok\"}");

        Response.End();
    }

    public bool addorder(OrderResultData model)
    {

        shopeleCustorder dal = new shopeleCustorder();

        CustorderInfo infos = new CustorderInfo();
        infos.orderid = "e" + model.id.ToString();

        if (dal.GetCount("orderid = '" + infos.orderid + "'") > 0)
        {
            return true;
        }

        //1.加到系统，
        Custorder ordermodel = new Custorder();
        decimal allfoodmoney = 0;

        taobaoAPIAcountInfo bdrecords = new taobaoAPIAcount().GetList(1, 1, "linkurl='" + model.shopId + "'", "lasttime", 1).FirstOrDefault();
        if (bdrecords == null)
        {
            HJlog.toLog(" 饿了么商家（" + model.shopName + "）未绑定");
            return true;
        }


        int qty = 0;
        PointsInfo togomodel = new Points().GetSendFeeModel(bdrecords.Status);


        IList<Hangjing.Model.ETogoShoppingCart> Foods = new List<Hangjing.Model.ETogoShoppingCart>();

        Hangjing.Model.ETogoShoppingCart myshopcart = new Hangjing.Model.ETogoShoppingCart();
        myshopcart.TogoId = togomodel.Unid;
        myshopcart.sendfree = 0;
        //满多少元免配送费未处理
        myshopcart.ItemList = null;

        IList<ETogoShoppingCartInfo> foodlist = new List<ETogoShoppingCartInfo>();



        foreach (var item in model.groups)
        {
            foreach (var food in item.items)
            {
                ETogoShoppingCartInfo cartfood = new ETogoShoppingCartInfo();

                cartfood.PId = 0;
                cartfood.PName = food.name;
                cartfood.PNum = food.quantity;
                cartfood.PPrice = food.price;
                cartfood.Currentprice = cartfood.PPrice;
                cartfood.Foodcurrentprice = cartfood.PPrice;
                cartfood.Remark = "";


                allfoodmoney += cartfood.PPrice * cartfood.PNum;
                qty += cartfood.PNum;

                foodlist.Add(cartfood);
            }

        }

        myshopcart.ItemList = foodlist;
        Foods.Add(myshopcart);



        infos.OrderChecker = 0;
        infos.OrderAddress = model.shopName;

        infos.OrderRcver = model.consignee;
        infos.OrderComm = model.phoneList[0];
        infos.OrderAttach = "";

        string Remark = model.description;

        if (model.invoiced == "true")
        {
            Remark += "[发票：" + model.invoice + "]";
        }
        Remark += "[饿了么" + model.daySn + "号单]";

        infos.OrderAttach = Remark;

        infos.AddressText = model.address;
        infos.SendTime = DateTime.Now.AddMinutes(50);
        if (model.deliverTime != null && model.deliverTime != "")
        {
            infos.SendTime = Convert.ToDateTime(model.deliverTime.ToString());
        }


        infos.cityid = 0;
        infos.fromweb = ((int)OrderSource.api).ToString();
        infos.tempcode = "";
        infos.tempcode = "";
        infos.CustomerName = "";
        infos.ReveVar1 = togomodel.sentorg;



        infos.OldPrice = allfoodmoney;

        infos.OrderSums = model.totalPrice;


        infos.TogoId = togomodel.Unid;
        infos.P2Sign = "";
        infos.paytime = Convert.ToDateTime("1970-1-1");
        infos.paymode = 4;
        infos.ReveDate1 = DateTime.Now;

        infos.cardids = "";


        infos.settlecycle = togomodel.PType;
        infos.Advance = 0;
        infos.Mergeorderremark = "";
        infos.SystemUserId = 0;
        infos.IsShopSet = 0;
        infos.ReveDate1 = DateTime.Now;

        IList<Hangjing.Model.ETogoShoppingCart> list = Foods;

        string ulat = "0";
        string ulng = "0";

        //SendInfo send = new SendInfo();

        string[] latlng = model.deliveryGeo.Split(',');
        //调用百度接口转换坐标
        BaiduMap map = new BaiduMap(latlng[1], latlng[0]); 
        string[] newbdlatlgn = map.getBaiDuLatLng();

        ulat = newbdlatlgn[0];
        ulng = newbdlatlgn[1];

        SendfeeInfo info = new SendfeeInfo();
        info.ShopID = togomodel.Unid;
        info.userpay = infos.OrderSums;
        info.latlng = new latlnginfo();
        info.latlng.ulat = ulat;
        info.latlng.ulng = ulng;

        SendFee fee = new SendFee(info);
        SendInfo senddata = fee.getSendFee();

        infos.Commission = WebHelper.getShopCommission(allfoodmoney, togomodel);
        infos.shopdiscountmoney = senddata.sendmoney;
        infos.cardpay = senddata.Distance;

        infos.ReveVar2 = "{'ulat':'" + ulat + "','ulng':'" + ulng + "','slat':'" + togomodel.Lat + "','slng':'" + togomodel.Lng + "'}";

        foreach (Hangjing.Model.ETogoShoppingCart item in Foods)
        {
            item.latlng = infos.ReveVar2;
        }

        if (model.onlinePaid == "true")
        {
            infos.paystate = 1;
            infos.paymoney = model.totalPrice;
            infos.paymode = 1;
            infos.paytime = DateTime.Now;

        }

        ////这里进行所有的判断
        IList<ROrderinfo> mylist = dal.SubmitOrder(Foods, infos);

        if (mylist != null)
        {
            if (infos.paystate == 1)
            {
                dal.UpdatePayState(infos);
            }

            WebUtility.excutesql("UPDATE dbo.shopeleCustorder SET systemuserid = 1 WHERE orderid = '" + infos.orderid + "'");
            if (togomodel.PosSrvAd.Trim() == "1")//自动导入正式系统
            {
                WebHelper.sendMTOrder2system(infos.orderid);
            }

            return true;

        }
        else
        {
            return false;

        }
    }
}